package com.yc.cloud.admin.controller;

import com.yc.cloud.admin.config.AlarmEmailProperties;
import com.yc.cloud.admin.service.AlarmEmailService;
import com.yc.cloud.common.basic.api.ResponseResult;
import com.yc.cloud.entity.AlarmRecord;
import com.yc.cloud.mapper.AlarmRecordMapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 邮件功能测试接口
 *
 * @author JackGu
 * @since 2025-11-07
 */
@Slf4j
@RestController
@RequestMapping("/test/email")
@Tag(name = "邮件功能测试")
public class EmailTestController {

    @Resource
    private JavaMailSender mailSender;

    @Resource
    private AlarmEmailService alarmEmailService;

    @Resource
    private AlarmEmailProperties alarmEmailProperties;

    @Resource
    private AlarmRecordMapper alarmRecordMapper;

    @Value("${spring.mail.username}")
    private String from;

    @Operation(summary = "发送测试邮件（简单文本）")
    @GetMapping("/send-simple")
    public ResponseResult<String> sendSimpleEmail(
            @Parameter(description = "收件人邮箱") @RequestParam String to) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");

            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject("【测试邮件】邮件功能测试 - " + 
                LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            helper.setText("这是一封测试邮件，发送时间：" + LocalDateTime.now());

            mailSender.send(message);
            
            log.info("测试邮件发送成功: to={}", to);
            return ResponseResult.success("邮件发送成功！请检查收件箱: " + to);
            
        } catch (MessagingException e) {
            log.error("测试邮件发送失败: to={}", to, e);
            return ResponseResult.failed("邮件发送失败: " + e.getMessage());
        }
    }

    @Operation(summary = "发送测试邮件（HTML格式）")
    @GetMapping("/send-html")
    public ResponseResult<String> sendHtmlEmail(
            @Parameter(description = "收件人邮箱") @RequestParam String to) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");

            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject("【测试邮件】HTML格式测试");
            
            String htmlContent = """
                <!DOCTYPE html>
                <html>
                <head>
                    <style>
                        body { font-family: Arial, sans-serif; }
                        .container { padding: 20px; background-color: #f5f5f5; }
                        .header { background-color: #4CAF50; color: white; padding: 20px; text-align: center; }
                        .content { background-color: white; padding: 20px; margin-top: 20px; }
                        .footer { margin-top: 20px; text-align: center; color: #666; }
                    </style>
                </head>
                <body>
                    <div class="container">
                        <div class="header">
                            <h1>✅ 邮件功能测试成功</h1>
                        </div>
                        <div class="content">
                            <h2>测试信息</h2>
                            <p><strong>发送时间:</strong> %s</p>
                            <p><strong>发件人:</strong> %s</p>
                            <p><strong>收件人:</strong> %s</p>
                            <p>如果你能看到这封邮件，说明邮件配置正确！</p>
                        </div>
                        <div class="footer">
                            <p>本邮件由 AI智能监控系统 自动发送</p>
                        </div>
                    </div>
                </body>
                </html>
                """.formatted(
                    LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")),
                    from,
                    to
                );
            
            helper.setText(htmlContent, true);

            mailSender.send(message);
            
            log.info("HTML测试邮件发送成功: to={}", to);
            return ResponseResult.success("HTML邮件发送成功！请检查收件箱: " + to);
            
        } catch (MessagingException e) {
            log.error("HTML测试邮件发送失败: to={}", to, e);
            return ResponseResult.failed("邮件发送失败: " + e.getMessage());
        }
    }

    @Operation(summary = "发送告警邮件测试（使用真实告警记录）")
    @GetMapping("/send-alarm/{alarmId}")
    public ResponseResult<String> sendAlarmEmailTest(
            @Parameter(description = "告警记录ID") @PathVariable Long alarmId) {
        try {
            // 查询告警记录
            AlarmRecord alarmRecord = alarmRecordMapper.selectById(alarmId);
            if (alarmRecord == null) {
                return ResponseResult.failed("告警记录不存在: ID=" + alarmId);
            }

            // 发送告警邮件
            alarmEmailService.sendAlarmEmail(alarmRecord);
            
            log.info("告警邮件测试发送成功: alarmId={}", alarmId);
            return ResponseResult.success("告警邮件发送成功！收件人: " + 
                alarmEmailProperties.getRecipientList());
            
        } catch (Exception e) {
            log.error("告警邮件测试发送失败: alarmId={}", alarmId, e);
            return ResponseResult.failed("邮件发送失败: " + e.getMessage());
        }
    }
}

